package com.lemon.smartsafetynew.ui.fragment.user.register;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafetynew.entity.event.user.PageEvent;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.util.common.AppSharePreferenceUtil;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Andrew on 2017/7/18.
 */

public class UserRegisterStepTwoFragment extends BaseFragment {


    @Bind(R.id.title_tips)
    TextView titleTips;
    @Bind(R.id.auth_code_edit)
    EditText authCodeEdit;
    @Bind(R.id.auth_code_btn)
    Button authCodeBtn;
    @Bind(R.id.error_info_tv)
    TextView errorInfoTv;


    private MaterialDialog materialDialog;

    private Timer timer;
    private int timeUnit;
    private int times;
    private int totalTime;

    private String telephone;


    @Override
    protected void getBaseArguments() {

    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_user_register_step_two;
    }

    @Override
    protected void initViews() {

        initData();

        titleTips.setText("");
        authCodeBtn.setText(getString(R.string.get_auth_code));

    }

    @OnClick({R.id.auth_code_btn, R.id.next_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.auth_code_btn:
                errorInfoTv.setText("");
                // ===== 请求发送验证码到手机 =====
                AccountServices.init().registerAskAuthCode(telephone);

                break;
            case R.id.next_btn:
                errorInfoTv.setText("");

                String authCode = authCodeEdit.getText().toString().trim();
                if(checkAuthCode(authCode) && matcherAuthCode(authCode)) {
                    // ===== 验证验证码 =====
                    AccountServices.init().registerCheckAuthCode(telephone, authCode);
                } else {
                    errorInfoTv.setText(getString(R.string.auth_code_error));
                }

                break;
        }
    }

    private void initData() {
        telephone = AppSharePreferenceUtil.getInstance().getString(SafeCloudConstants.USER_TELEPHONE_NUMBER, "");
        timeUnit = SafeCloudConstants.SEND_SMS_UNIT; //一个时间单元是60s
        times = 1;

    }

    private boolean checkAuthCode(String authCode) {
        return !(null == authCode || "".equals(authCode));
    }

    private boolean matcherAuthCode(String telNum) {

        String pattern = "^\\d{4}$";
        Pattern mPattern = Pattern.compile(pattern);
        Matcher mMatcher = mPattern.matcher(telNum);

        return mMatcher.matches();
    }

    private void countDown() {

        authCodeBtn.setEnabled(false);

        totalTime = (timeUnit * times) > SafeCloudConstants.MAX_SEND_SMS_TIME ? SafeCloudConstants.MAX_SEND_SMS_TIME:(timeUnit * times); // Max value

        times++;

        timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                totalTime--;
                if (totalTime == 0) {
                    timer.cancel();
                    timer.purge();
                    timer = null;
                }
                AppService.getBus().post(new AppEvent());
            }
        }, 0, 1000);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }

        cancelDialog();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AppEvent event) {

        if (totalTime == 0) {
            authCodeBtn.setEnabled(true);
            authCodeBtn.setText(getString(R.string.get_auth_code));
        } else {
            authCodeBtn.setEnabled(false);
            authCodeBtn.setText(getString(R.string.get_auth_code) + "(" + totalTime + "s)");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent<String> event) {
        if (KeyConstants.URL_REGISTER_ASK_AUTH_CODE.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {


                countDown();
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();

                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    String telephoneNum = AppSharePreferenceUtil.getInstance().getString(SafeCloudConstants.USER_TELEPHONE_NUMBER, "");
                    titleTips.setText(getString(R.string.has_send_auth_code));
                    titleTips.append(telephoneNum);
                    Toast.makeText(getmContext(), "验证码已发送", Toast.LENGTH_SHORT).show();
                } else {
                    if (timer != null) {
                        timer.cancel();
                        timer.purge();
                        timer = null;
                        totalTime = 0;
                        times = 1;
                    }
                    Toast.makeText(getmContext(), "验证码发送失败", Toast.LENGTH_SHORT).show();
                }

            }
        } else if(KeyConstants.URL_REGISTER_CHECK_AUTH_CODE.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                showDialog();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                cancelDialog();

                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    AppService.getBus().post(new PageEvent());
                } else {
                    errorInfoTv.setText(event.getMsg());
                }
            }
        }
    }

    private void showDialog() {
        materialDialog = new MaterialDialog.Builder(getActivity())
                .content(R.string.please_wait)
                .progress(true, 0)
                .cancelable(false)
                .show();
    }

    private void cancelDialog() {
        if(materialDialog != null && materialDialog.isShowing()) {
            materialDialog.dismiss();
            materialDialog = null;
        }
    }
}
